package com.haiyou.dc.aggregate.list;

import java.util.Arrays;

/**
 * 添加get、set方法
 * 检查索引是否合法
 *
 * @param <E>
 */
public class MyArrayList04<E> {

    private Object[] elementData;
    private int size;
    private static final int DEFAULT_CAPACITY = 10;

    public MyArrayList04() {
        this.elementData = new Object[DEFAULT_CAPACITY];
    }

    public MyArrayList04(int capacity) {

        if (capacity < 0) {
            throw new RuntimeException("容器大小不能为负数");
        } else if (capacity == 0) {
            this.elementData = new Object[DEFAULT_CAPACITY];
        } else {
            this.elementData = new Object[capacity];
        }

    }

    public void add(E element) {

        if (size == elementData.length) {
            int newLength = elementData.length + (elementData.length >> 1);
            Object[] newArray = new Object[newLength];
            //数组拷贝，将原数组从0开始拷贝到新数组，从0开始，拷贝长度为原数组长度
//            System.arraycopy(elementData, 0, newArray, 0, elementData.length);
            //新数组指向老数组
//            elementData = newArray;
            elementData = Arrays.copyOf(elementData, newLength);
        }

        elementData[size++] = element;
    }

    public E get(int index) {
        checkRange(index);
        return (E) elementData[index];
    }

    public void set(E element, int index) {
        checkRange(index);
        elementData[index] = element;
    }

    /**
     * 索引检测
     *
     * @param index
     */
    private void checkRange(int index) {
        if (index < 0 || index >= size) {
            throw new RuntimeException("索引不合法:" + index);
        }
    }

//    @Override
//    public String toString() {
//        Joiner joiner2 = Joiner.on(",").skipNulls(); //过滤null
//        return joiner2.join(elementData);
//    }


    @Override
    public String toString() {
        return "MyArrayList04{" +
                "elementData=" + Arrays.toString(elementData) +
                ", size=" + size +
                '}';
    }

    public static void main(String[] args) {
        MyArrayList04<Integer> myArrayList01 = new MyArrayList04(0);
        System.out.println(myArrayList01);
        for (int i = 0; i < 40; i++) {
            myArrayList01.add(i);
        }

        System.out.println(myArrayList01);

        Integer number = myArrayList01.get(10);
        System.out.println(number);

        myArrayList01.set(20, 10);

        number = myArrayList01.get(39);
        System.out.println(number);
        System.out.println(myArrayList01);


    }
}
